#include<iostream>
#include<fstream>

using namespace std;

void file_wr();
void file_copy();

int main()
{   
    file_wr();
    file_copy();
    system("pause");
    return 0;
}

void file_wr(){
    char data[100];
    ofstream outfile;
    outfile.open("test.txt");
    cout << "Write to the file" << endl;
    cout << "Enter your name:" << endl;
    cin.getline(data, 100);
    outfile << data << endl;
    cout << "Enter your age:" << endl;
    cin >> data;
    cin.ignore();
    outfile << data << endl;
    outfile.close();
    //从文件读取数据
    ifstream infile;
    infile.open("test.txt");
    cout << "Read from the file" << endl;
    infile >> data;
    cout << data << endl;
    infile >> data;
    cout << data << endl;
    infile.close();
};

//将数据从一文件复制到另一文件中
void file_copy(void)
{
    char data[100];
    ifstream infile;
    ofstream outfile;
    infile.open("test.txt");
    outfile.open("test_1.txt");
    cout << "copy from test.txt to test_1.txt" << endl;
    while (!infile.eof())
    {
        infile >> data;
        //fstream读取txt文件时发现末尾一行会被读取两次，
        //可能是因为到达文件末尾时，eof仍然是false，只有继续往下读时才会变成true。
        if(infile.eof())    
            break;
        cout << data << endl;
        outfile << data << endl;
    }
    infile.close();
    outfile.close();
}